package com.heima.search.service.impl;

import com.heima.model.search.pojos.ApUserSearch;
import com.heima.search.service.ApUserSearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ApUserSearchServiceImpl implements ApUserSearchService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Async
    @Override
    public void insert(String keyword ,Integer userId) {
        //1.根据关键词查看mongoDB中是否有数据
        Query query = Query.query(Criteria.where("keyword").is(keyword).and("userId").is(userId));
        ApUserSearch search = mongoTemplate.findOne(query, ApUserSearch.class);
        //2.如果存在则更新词条的时间
        if (null != search){
            search.setCreatedTime(new Date());
            mongoTemplate.save(search);
            return;
        }
        //3.如果不存在，则查询当前登录用户的搜索记录
        query = Query.query(Criteria.where("userId").is(userId)).with(Sort.by(Sort.Direction.DESC, "createdTime"));
        List<ApUserSearch> list = mongoTemplate.find(query, ApUserSearch.class);
        //4.判断总记录数是否小于10，如果小于则直接存，如果大于则替换掉最老的记录
        search = new ApUserSearch();
        search.setUserId(userId);
        search.setKeyword(keyword);
        search.setCreatedTime(new Date());

        if (null != list && list.size() < 10 ){
            mongoTemplate.save(search);
        }else {
            ApUserSearch last = list.get(list.size() - 1);

            mongoTemplate.findAndReplace(Query.query(Criteria.where("'id").is(last.getId())),search);

        }
    }
}
